package com.jiao.service.impl;

import com.jiao.constants.Constants;
import com.jiao.domain.LoginUser;
import com.jiao.domain.Result;
import com.jiao.domain.VO.LikeVo;
import com.jiao.domain.entity.MsgNotify;
import com.jiao.mapper.MsgNotifyMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Service
public class LikeServiceImp_mysql {

    @Autowired
    MsgNotifyMapper notifyMapper;
    /*
     * 点赞操作
     * */
    public Boolean likeClick(Long articleId,String type,Long userId) {

        Integer isMumber = likerIsMumber(articleId, userId, type);

        if (Objects.equals(isMumber, 1)) {
            //删除数据库数据
            notifyDelete(articleId, userId, type);
            //修改缓存，该用户取消点赞
        } else {
            // 增加数据库数据
            if (!Objects.equals(notifyMapper.updateStatus(userId, articleId, type), 1)) {
                notifyMapper.insertMsgNotify(userId, articleId, type);
            }
            //修改缓存，点赞
        }

        return !Objects.equals(isMumber, 1);
    }
    /*
     * 判断该文章是否被该用户点赞
     * */
    private Integer likerIsMumber(Long articleId,Long userId,String type){
        return notifyMapper.isExist(userId,articleId,type);
    }

    /*
     * 取消点赞
     * */
    private void notifyDelete(Long articleId, Long userId, String type){
        notifyMapper.delete(new LambdaQueryWrapper<MsgNotify>()
                .eq(MsgNotify::getEntityId, articleId)
                .eq(MsgNotify::getOperatorId, userId)
                .eq(MsgNotify::getType, type));
    }

    public Result<LikeVo> like(Long articleId, String type) {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getSysUser().getId();

        //点赞操作，返回值是点赞状态
        Boolean ismember =likeClick(articleId,type,userId);

        //查看已有多少人点赞
        //Integer num = likeNumber(articleId);

        //TODO 向点赞的MQ队列去发送消息。在查询有多少未看点赞消息的service中，查询队列消息

        return Result.success(new LikeVo(1L,ismember));
    }

    /*
     * 获取文章总点击量
     * */
    private Integer likeNumber(Long articleId){
        return notifyMapper.selectCount(new LambdaQueryWrapper<MsgNotify>()
                .eq(MsgNotify::getEntityId, articleId)
                .eq(MsgNotify::getType, Constants.MSG_NOTIFY_LIKE_ARTICLE));
    }
}
